<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>fetch abort和fetch timeout</title>
</head>
<body>
    <input id="ipt" type='text' />
    <script>
        let ipt = document.querySelector('#ipt');

        /**
         * fetch timeout
         */
         function timeoutFunc() {
            let controller = new AbortController();
            let signal = controller.signal;

            //超时处理方法
            let timeoutPromise = (timeout) => {
                return new Promise((resolve, reject) => {
                    setTimeout(() => {
                        resolve(new Response("timeout", { status: 504, statusText: "timeout " }));
                        controller.abort();
                    }, timeout)
                })
            }

            //拉数据的请求方法
            let requestPromise = (url) => {
                return fetch(url, {
                    signal: signal
                })
            }

            Promise.race([timeoutPromise(4000), requestPromise("http://youyong.ba:8080/mock/609a94bd9fdbd7143b8d6737/aa/test")])
        }

        ipt.addEventListener("keyup", (e) => {
            timeoutFunc();
        });


        /**
         * fetch abort
         */
        // let k = 0;
        // let controllers = [];

        // async function cancelPromise(promise, abortHandle) {
            
        //     const abortFunc = new Promise((_,reject) => {
        //             abortHandle.cancel = function cannel(text) {
        //                 controllers[k].abort();
        //                 reject(text)
        //             }
        //         })

        //     let response = await Promise.race([
        //         promise,
        //         abortFunc
        //     ]);

        //     let res =  await response.json();
        //     console.log(res)
        // }

        // const abortFunc = {
        //     cancel: function () {

        //     }
        // }

        // function ajaxHandle(url) {
        //     //关闭上一个请求

        //     abortFunc.cancel('关闭上一个请求');
        //     k++;
        //     controllers[k] = new AbortController();
        //     signal = controllers[k].signal;

        //     cancelPromise(fetch(url, {
        //         signal: signal
        //     }), abortFunc)
            
        // }

        // ipt.addEventListener('keyup', function (e) {
        //     ajaxHandle('http://youyong.ba:8080/mock/609a94bd9fdbd7143b8d6737/aa/test');
        // });
    </script>
</body>
</html>